/**********************************************************************************************************************
 * SplendidCRM is a Customer Relationship Management program created by SplendidCRM Software, Inc. 
 * Copyright (C) 2005-2011 SplendidCRM Software, Inc. All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify it under the terms of the 
 * GNU Affero General Public License as published by the Free Software Foundation, either version 3 
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License along with this program. 
 * If not, see <http://www.gnu.org/licenses/>. 
 * 
 * You can contact SplendidCRM Software, Inc. at email address support@splendidcrm.com. 
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3, 
 * the Appropriate Legal Notices must display the following words on all interactive user interfaces: 
 * "Copyright (C) 2005-2011 SplendidCRM Software, Inc. All rights reserved."
 *********************************************************************************************************************/
using System;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using SplendidCRM._controls;

namespace SplendidCRM.Leads
{
	/// <summary>
	///		Summary description for ConvertView.
	/// </summary>
	public class ConvertView : SplendidControl
	{
		protected _controls.ModuleHeader   ctlModuleHeader  ;
		protected _controls.DynamicButtons ctlDynamicButtons;

		protected Guid            gID                             ;
		protected HtmlTable       tblMain                         ;
		protected Label           lblDATEFORMAT                   ;

		protected TextBox                txtCONTACT_NOTES_NAME                ;
		protected RequiredFieldValidator reqCONTACT_NOTES_NAME                ;
		protected TextBox                txtCONTACT_NOTES_NAME_DESCRIPTION    ;


		protected CheckBox               chkCreateAccount                     ;
		protected HtmlInputHidden        txtSELECT_ACCOUNT_ID                 ;
		protected RequiredFieldValidatorForHiddenInputs reqSELECT_ACCOUNT_ID  ;
		protected TextBox                txtSELECT_ACCOUNT_NAME               ;
		// 11/03/2008 Paul.  Allow selection of an opportunity. 
		protected HtmlInputHidden        txtSELECT_OPPORTUNITY_ID             ;
		protected TextBox                txtSELECT_OPPORTUNITY_NAME           ;
		protected RequiredFieldValidatorForHiddenInputs reqSELECT_OPPORTUNITY_ID;

		protected TextBox                txtACCOUNT_NAME                      ;
		protected RequiredFieldValidator reqACCOUNT_NAME                      ;
		protected TextBox                txtACCOUNT_DESCRIPTION               ;
		protected TextBox                txtACCOUNT_PHONE_WORK                ;
		protected TextBox                txtACCOUNT_WEBSITE                   ;
		protected TextBox                txtACCOUNT_NOTES_NAME                ;
		protected RequiredFieldValidator reqACCOUNT_NOTES_NAME                ;
		protected TextBox                txtACCOUNT_NOTES_NAME_DESCRIPTION    ;

		protected CheckBox               chkCreateOpportunity                 ;
		protected TextBox                txtOPPORTUNITY_NAME                  ;
		protected RequiredFieldValidator reqOPPORTUNITY_NAME                  ;
		protected TextBox                txtOPPORTUNITY_DESCRIPTION           ;
		protected DatePicker             ctlOPPORTUNITY_DATE_CLOSED           ;
		protected DropDownList           lstOPPORTUNITY_SALES_STAGE           ;
		protected TextBox                txtOPPORTUNITY_AMOUNT                ;
		protected RequiredFieldValidator reqOPPORTUNITY_AMOUNT                ;
		protected TextBox                txtOPPORTUNITY_NOTES_NAME            ;
		protected TextBox                txtOPPORTUNITY_NOTES_NAME_DESCRIPTION;
		protected RequiredFieldValidator reqOPPORTUNITY_NOTES_NAME            ;

		protected CheckBox               chkCreateAppointment                 ;
		protected RadioButton            radScheduleCall                      ;
		protected RadioButton            radScheduleMeeting                   ;
		protected TextBox                txtAPPOINTMENT_NAME                  ;
		protected TextBox                txtAPPOINTMENT_DESCRIPTION           ;
		protected RequiredFieldValidator reqAPPOINTMENT_NAME                  ;
		protected DatePicker             ctlAPPOINTMENT_DATE_START            ;
		protected TextBox                txtAPPOINTMENT_TIME_START            ;
		protected RequiredFieldValidator reqAPPOINTMENT_TIME_START            ;

		protected void Page_Command(Object sender, CommandEventArgs e)
		{
			if ( e.CommandName == "Save" )
			{
				try
				{
					// 01/31/2006 Paul.  Enable validator before validating page. 
					this.ValidateEditViewFields(m_sMODULE + "." + LayoutEditView);
					// 05/25/2011 Paul.  Apply Business Rules. 
					this.ApplyEditViewValidationEventRules(m_sMODULE + "." + LayoutEditView);
					if ( Page.IsValid )
					{
						// 02/27/2006 Paul.  Fix condition on notes.  Enable only if text exists. 
						txtCONTACT_NOTES_NAME_DESCRIPTION.Text = txtCONTACT_NOTES_NAME_DESCRIPTION.Text.Trim();
						reqCONTACT_NOTES_NAME    .Enabled = !Sql.IsEmptyString(txtCONTACT_NOTES_NAME_DESCRIPTION.Text    );
						reqCONTACT_NOTES_NAME    .Validate();

						txtACCOUNT_NOTES_NAME_DESCRIPTION.Text = txtACCOUNT_NOTES_NAME_DESCRIPTION.Text.Trim();
						reqACCOUNT_NOTES_NAME    .Enabled = !Sql.IsEmptyString(txtACCOUNT_NOTES_NAME_DESCRIPTION.Text    );
						reqACCOUNT_NOTES_NAME    .Validate();
						
						txtOPPORTUNITY_NOTES_NAME_DESCRIPTION.Text = txtOPPORTUNITY_NOTES_NAME_DESCRIPTION.Text.Trim();
						reqOPPORTUNITY_NOTES_NAME.Enabled = !Sql.IsEmptyString(txtOPPORTUNITY_NOTES_NAME_DESCRIPTION.Text);
						reqOPPORTUNITY_NOTES_NAME.Validate();

						// 01/31/2006 Paul.  SelectAccount is required if not creating an account but creating an opportunity. 
						reqSELECT_ACCOUNT_ID     .Enabled = !chkCreateAccount.Checked && chkCreateOpportunity.Checked;
						reqSELECT_ACCOUNT_ID     .Validate();
						reqACCOUNT_NAME          .Enabled = chkCreateAccount.Checked ;
						reqACCOUNT_NAME          .Validate();
						reqOPPORTUNITY_NAME      .Enabled = chkCreateOpportunity.Checked;
						reqOPPORTUNITY_NAME      .Validate();
						reqOPPORTUNITY_AMOUNT    .Enabled = chkCreateOpportunity.Checked;
						reqOPPORTUNITY_AMOUNT    .Validate();
						reqAPPOINTMENT_NAME      .Enabled = chkCreateAppointment.Checked;
						reqAPPOINTMENT_NAME      .Validate();
						reqAPPOINTMENT_TIME_START.Enabled = chkCreateAppointment.Checked;
						reqAPPOINTMENT_TIME_START.Validate();
						if ( chkCreateAppointment.Checked )
							ctlAPPOINTMENT_DATE_START.Validate();
					}
					if ( Page.IsValid )
					{
						// 01/15/2009 Paul.  When converting a lead, the custom module is the destination module. 
						// 09/09/2009 Paul.  Use the new function to get the table name. 
						string sTABLE_NAME = Crm.Modules.TableName("Contacts");
						DataTable dtCustomFields = SplendidCache.FieldsMetaData_Validated(sTABLE_NAME);
						DbProviderFactory dbf = DbProviderFactories.GetFactory();
						using ( IDbConnection con = dbf.CreateConnection() )
						{
							con.Open();
							// 05/25/2011 Paul.  Use the current values for any that are not defined in the edit view. 
							DataRow   rowCurrent = null;
							DataTable dtCurrent  = new DataTable();
							if ( !Sql.IsEmptyGuid(gID) )
							{
								string sSQL ;
								sSQL = "select *              " + ControlChars.CrLf
								     + "  from vwLEADS_Convert" + ControlChars.CrLf;
								using ( IDbCommand cmd = con.CreateCommand() )
								{
									cmd.CommandText = sSQL;
									Security.Filter(cmd, m_sMODULE, "edit");
									Sql.AppendParameter(cmd, gID, "ID", false);
									using ( DbDataAdapter da = dbf.CreateDataAdapter() )
									{
										((IDbDataAdapter)da).SelectCommand = cmd;
										da.Fill(dtCurrent);
										if ( dtCurrent.Rows.Count > 0 )
										{
											rowCurrent = dtCurrent.Rows[0];
										}
									}
								}
							}
							
							// 05/25/2011 Paul.  Apply Business Rules. 
							this.ApplyEditViewPreSaveEventRules(m_sMODULE + "." + LayoutEditView, rowCurrent);
							
							// 10/07/2009 Paul.  We need to create our own global transaction ID to support auditing and workflow on SQL Azure, PostgreSQL, Oracle, DB2 and MySQL. 
							using ( IDbTransaction trn = Sql.BeginTransaction(con) )
							{
								try
								{
									Guid gCONTACT_ID     = Guid.Empty;
									Guid gACCOUNT_ID     = Guid.Empty;
									Guid gOPPORTUNITY_ID = Guid.Empty;
									Guid gAPPOINTMENT_ID = Guid.Empty;
									
									// 01/31/2006 Paul.  Create the contact first so that it can be used as the parent of the related records. 
									// We would normally create the related records second, but then it will become a pain to update the Contact ACCOUNT_ID field. 
									SqlProcs.spCONTACTS_New
										( ref gCONTACT_ID
										, new DynamicControl(this, rowCurrent, "FIRST_NAME"                ).Text
										, new DynamicControl(this, rowCurrent, "LAST_NAME"                 ).Text
										, new DynamicControl(this, rowCurrent, "PHONE_WORK"                ).Text
										, new DynamicControl(this, rowCurrent, "EMAIL1"                    ).Text
										, trn
										);
									
									if ( chkCreateAccount.Checked )
									{
										// 08/06/2009 Paul.  ACCOUNT_NUMBER now uses our number sequence table. 
										// 04/07/2010 Paul.  Add EXCHANGE_FOLDER. 
										// 05/25/2011 Paul.  Instead of using ViewState, load the previous record and let the DynamicControl use it if necessary. 
										SqlProcs.spACCOUNTS_Update
											( ref gACCOUNT_ID
											, Security.USER_ID
											, txtACCOUNT_NAME.Text
											, String.Empty
											, Guid.Empty
											, String.Empty
											, String.Empty
											, new DynamicControl(this, rowCurrent, "PHONE_FAX"                 ).Text
											, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_STREET"    ).Text
											, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_CITY"      ).Text
											, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_STATE"     ).Text
											, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_POSTALCODE").Text
											, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_COUNTRY"   ).Text
											, txtACCOUNT_DESCRIPTION.Text
											, String.Empty
											, txtACCOUNT_PHONE_WORK.Text
											, new DynamicControl(this, rowCurrent, "PHONE_OTHER"               ).Text
											, new DynamicControl(this, rowCurrent, "EMAIL1"                    ).Text
											, new DynamicControl(this, rowCurrent, "EMAIL2"                    ).Text
											, txtACCOUNT_WEBSITE.Text
											, String.Empty
											, String.Empty
											, String.Empty
											, String.Empty
											, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_STREET"        ).Text
											, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_CITY"          ).Text
											, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_STATE"         ).Text
											, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_POSTALCODE"    ).Text
											, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_COUNTRY"       ).Text
											, String.Empty  // ACCOUNT_NUMBER
											, new DynamicControl(this, rowCurrent, "TEAM_ID"                   ).ID
											, new DynamicControl(this, rowCurrent, "TEAM_SET_LIST"             ).Text
											, new DynamicControl(this, "EXCHANGE_FOLDER" ).Checked
											, trn
											);
										
										if ( !Sql.IsEmptyString(txtACCOUNT_NOTES_NAME.Text) )
										{
											Guid gNOTE_ID = Guid.Empty;
											SqlProcs.spNOTES_Update
												( ref gNOTE_ID
												, txtACCOUNT_NOTES_NAME.Text
												, "Accounts"
												, gACCOUNT_ID
												, Guid.Empty
												, txtACCOUNT_NOTES_NAME_DESCRIPTION.Text
												, new DynamicControl(this, rowCurrent, "TEAM_ID"                   ).ID
												, new DynamicControl(this, rowCurrent, "TEAM_SET_LIST"             ).Text
												, trn
												);
										}
									}
									else
									{
										gACCOUNT_ID = Sql.ToGuid(txtSELECT_ACCOUNT_ID.Value);
									}
									if ( chkCreateOpportunity.Checked )
									{
										// 04/07/2010 Paul.  Add EXCHANGE_FOLDER. 
										SqlProcs.spOPPORTUNITIES_Update
											( ref gOPPORTUNITY_ID
											, Security.USER_ID
											, gACCOUNT_ID
											, txtOPPORTUNITY_NAME.Text
											, String.Empty
											, new DynamicControl(this, rowCurrent, "LEAD_SOURCE"               ).SelectedValue
											, Sql.ToDecimal(txtOPPORTUNITY_AMOUNT.Text)
											, Guid.Empty
											, T10n.ToServerTime(ctlOPPORTUNITY_DATE_CLOSED.Value)
											, String.Empty
											, lstOPPORTUNITY_SALES_STAGE.SelectedValue
											, (float) 0.0
											, txtOPPORTUNITY_DESCRIPTION.Text
											, String.Empty
											, Guid.Empty
											, String.Empty  // 11/02/2006 Paul.  ACCOUNT_NAME is only used for import. 
											, new DynamicControl(this, rowCurrent, "TEAM_ID"                   ).ID
											, new DynamicControl(this, rowCurrent, "TEAM_SET_LIST"             ).Text
											, new DynamicControl(this, rowCurrent, "CAMPAIGN_ID"               ).ID  // 12/16/2009 Paul.  Add Campaign tracking. 
											, new DynamicControl(this, "EXCHANGE_FOLDER" ).Checked
											, trn
											);
										if ( !Sql.IsEmptyString(txtOPPORTUNITY_NOTES_NAME.Text) )
										{
											Guid gNOTE_ID = Guid.Empty;
											SqlProcs.spNOTES_Update
												( ref gNOTE_ID
												, txtOPPORTUNITY_NOTES_NAME.Text
												, "Opportunities"
												, gOPPORTUNITY_ID
												, Guid.Empty
												, txtOPPORTUNITY_NOTES_NAME_DESCRIPTION.Text
												, new DynamicControl(this, rowCurrent, "TEAM_ID"                   ).ID
												, new DynamicControl(this, rowCurrent, "TEAM_SET_LIST"             ).Text
												, trn
												);
										}
										// 03/04/2006 Paul.  Must be included in the transaction, otherwise entire operation will fail with a timeout message. 
										SqlProcs.spOPPORTUNITIES_CONTACTS_Update(gOPPORTUNITY_ID, gCONTACT_ID, String.Empty, trn);
									}
									else
									{
										// 11/03/2008 Paul.  Allow selection of an opportunity. 
										gOPPORTUNITY_ID = Sql.ToGuid(txtSELECT_OPPORTUNITY_ID.Value);
									}
									if ( chkCreateAppointment.Checked )
									{
										DateTime dtDATE_START = T10n.ToServerTime(Sql.ToDateTime(ctlAPPOINTMENT_DATE_START.DateText + " " + txtAPPOINTMENT_TIME_START.Text));
										if ( radScheduleCall.Checked )
										{
											SqlProcs.spCALLS_Update
												( ref gAPPOINTMENT_ID
												, Security.USER_ID
												, txtAPPOINTMENT_NAME.Text
												, 1
												, 0
												, dtDATE_START
												, "Accounts"
												, Guid.Empty
												, "Planned"
												, "Outbound"
												, -1
												, txtAPPOINTMENT_DESCRIPTION.Text
												, gCONTACT_ID.ToString()         // 01/31/2006 Paul.  This is were we relate this call to the contact. 
												, new DynamicControl(this, rowCurrent, "TEAM_ID"                   ).ID
												, new DynamicControl(this, rowCurrent, "TEAM_SET_LIST"             ).Text
												, trn
												);
										}
										else
										{
											SqlProcs.spMEETINGS_Update
												( ref gAPPOINTMENT_ID
												, Security.USER_ID
												, txtAPPOINTMENT_NAME.Text
												, String.Empty
												, 1
												, 0
												, dtDATE_START
												, "Planned"
												, "Accounts"
												, Guid.Empty
												, -1
												, txtAPPOINTMENT_DESCRIPTION.Text
												, gCONTACT_ID.ToString()         // 01/31/2006 Paul.  This is were we relate this meeting to the contact. 
												, new DynamicControl(this, rowCurrent, "TEAM_ID"                   ).ID
												, new DynamicControl(this, rowCurrent, "TEAM_SET_LIST"             ).Text
												, trn
												);
										}
									}
									// 05/25/2011 Paul.  Instead of using ViewState, load the previous record and let the DynamicControl use it if necessary. 
									SqlProcs.spCONTACTS_ConvertLead
										( ref gCONTACT_ID
										, gID                                   // 01/31/2006 Paul.  Update the Lead with this contact. 
										, Security.USER_ID
										, new DynamicControl(this, rowCurrent, "SALUTATION"                ).SelectedValue
										, new DynamicControl(this, rowCurrent, "FIRST_NAME"                ).Text
										, new DynamicControl(this, rowCurrent, "LAST_NAME"                 ).Text
										, gACCOUNT_ID
										, new DynamicControl(this, rowCurrent, "LEAD_SOURCE"               ).SelectedValue
										, new DynamicControl(this, rowCurrent, "TITLE"                     ).Text
										, new DynamicControl(this, rowCurrent, "DEPARTMENT"                ).Text
										, new DynamicControl(this, rowCurrent, "DO_NOT_CALL"               ).Checked
										, new DynamicControl(this, rowCurrent, "PHONE_HOME"                ).Text
										, new DynamicControl(this, rowCurrent, "PHONE_MOBILE"              ).Text
										, new DynamicControl(this, rowCurrent, "PHONE_WORK"                ).Text
										, new DynamicControl(this, rowCurrent, "PHONE_OTHER"               ).Text
										, new DynamicControl(this, rowCurrent, "PHONE_FAX"                 ).Text
										, new DynamicControl(this, rowCurrent, "EMAIL1"                    ).Text
										, new DynamicControl(this, rowCurrent, "EMAIL2"                    ).Text
										, new DynamicControl(this, rowCurrent, "EMAIL_OPT_OUT"             ).Checked
										, new DynamicControl(this, rowCurrent, "INVALID_EMAIL"             ).Checked
										, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_STREET"    ).Text
										, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_CITY"      ).Text
										, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_STATE"     ).Text
										, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_POSTALCODE").Text
										, new DynamicControl(this, rowCurrent, "PRIMARY_ADDRESS_COUNTRY"   ).Text
										, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_STREET"        ).Text
										, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_CITY"          ).Text
										, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_STATE"         ).Text
										, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_POSTALCODE"    ).Text
										, new DynamicControl(this, rowCurrent, "ALT_ADDRESS_COUNTRY"       ).Text
										, new DynamicControl(this, rowCurrent, "DESCRIPTION"               ).Text
										, gOPPORTUNITY_ID
										, txtOPPORTUNITY_NAME.Text
										, txtOPPORTUNITY_AMOUNT.Text
										, new DynamicControl(this, rowCurrent, "CAMPAIGN_ID"               ).ID  // 12/16/2009 Paul.  Add Campaign tracking. 
										, new DynamicControl(this, rowCurrent, "TEAM_ID"                   ).ID
										, new DynamicControl(this, rowCurrent, "TEAM_SET_LIST"             ).Text
										, trn
										);
									if ( !Sql.IsEmptyString(txtCONTACT_NOTES_NAME.Text) )
									{
										Guid gNOTE_ID = Guid.Empty;
										SqlProcs.spNOTES_Update
											( ref gNOTE_ID
											, txtCONTACT_NOTES_NAME.Text
											, String.Empty
											, Guid.Empty
											, gCONTACT_ID
											, txtCONTACT_NOTES_NAME_DESCRIPTION.Text
											, new DynamicControl(this, rowCurrent, "TEAM_ID"                   ).ID
											, new DynamicControl(this, rowCurrent, "TEAM_SET_LIST"             ).Text
											, trn
											);
									}
									// 02/26/2009 Paul.  We need to update the gCONTACT_ID, not the gID (which does nothing because it is an ID in the LEADS table).
									SplendidDynamic.UpdateCustomFields(this, trn, gCONTACT_ID, sTABLE_NAME, dtCustomFields);
									trn.Commit();
								}
								catch(Exception ex)
								{
									trn.Rollback();
									SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
									ctlDynamicButtons.ErrorText = ex.Message;
									return;
								}
							}
						}
						// 05/25/2011 Paul.  Apply Business Rules. 
						this.ApplyEditViewPostSaveEventRules(m_sMODULE + "." + LayoutEditView);
						
						Response.Redirect("view.aspx?ID=" + gID.ToString());
					}
				}
				catch(Exception ex)
				{
					SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
					ctlDynamicButtons.ErrorText = ex.Message;
				}
			}
			else if ( e.CommandName == "Cancel" )
			{
				if ( Sql.IsEmptyGuid(gID) )
					Response.Redirect("default.aspx");
				else
					Response.Redirect("view.aspx?ID=" + gID.ToString());
			}
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			try
			{
				// 10/18/2010 Paul.  The required fields need to be bound manually. 
				reqSELECT_OPPORTUNITY_ID.DataBind();
				reqSELECT_ACCOUNT_ID.DataBind();
				gID = Sql.ToGuid(Request["ID"]);
				SetPageTitle(L10n.Term(".moduleList." + m_sMODULE));
				if ( !IsPostBack )
				{
					lblDATEFORMAT.Text = "(" + Session["USER_SETTINGS/DATEFORMAT"] + ")";
					lstOPPORTUNITY_SALES_STAGE.DataSource = SplendidCache.List("sales_stage_dom");
					lstOPPORTUNITY_SALES_STAGE.DataBind();

					chkCreateAccount    .Attributes.Add("onclick", "return ToggleCreateAccount();");
					chkCreateOpportunity.Attributes.Add("onclick", "return ToggleCreateOpportunity();");
					chkCreateAppointment.Attributes.Add("onclick", "return toggleDisplay('divCreateAppointment');");

					if ( !Sql.IsEmptyGuid(gID) )
					{
						DbProviderFactory dbf = DbProviderFactories.GetFactory();
						using ( IDbConnection con = dbf.CreateConnection() )
						{
							string sSQL ;
							sSQL = "select *              " + ControlChars.CrLf
							     + "  from vwLEADS_Convert" + ControlChars.CrLf;
							using ( IDbCommand cmd = con.CreateCommand() )
							{
								cmd.CommandText = sSQL;
								// 05/25/2011 Paul.  Use new Security.Filter() function to apply Team and ACL security rules.
								Security.Filter(cmd, m_sMODULE, "edit");
								Sql.AppendParameter(cmd, gID, "ID", false);
								con.Open();

								if ( bDebug )
									RegisterClientScriptBlock("SQLCode", Sql.ClientScriptBlock(cmd));

								// 11/22/2010 Paul.  Convert data reader to data table for Rules Wizard. 
								using ( DbDataAdapter da = dbf.CreateDataAdapter() )
								{
									((IDbDataAdapter)da).SelectCommand = cmd;
									using ( DataTable dtCurrent = new DataTable() )
									{
										da.Fill(dtCurrent);
										if ( dtCurrent.Rows.Count > 0 )
										{
											DataRow rdr = dtCurrent.Rows[0];
											// 05/25/2011 Paul.  Apply Business Rules. 
											this.ApplyEditViewPreLoadEventRules(m_sMODULE + "." + LayoutEditView, rdr);
											
											ctlModuleHeader.Title = L10n.Term("Leads.LBL_CONVERTLEAD");
											SetPageTitle(L10n.Term(".moduleList." + m_sMODULE) + " - " + ctlModuleHeader.Title);
											
											txtACCOUNT_NAME          .Text  = Sql.ToString(rdr["ACCOUNT_NAME"]);
											txtACCOUNT_PHONE_WORK    .Text  = Sql.ToString(rdr["PHONE_WORK"  ]);
											// 01/31/2006 Paul.  Default start date and time is now. 
											ctlAPPOINTMENT_DATE_START.Value = T10n.FromServerTime(DateTime.Now);
											txtAPPOINTMENT_TIME_START.Text  = T10n.FromServerTime(DateTime.Now).ToShortTimeString();
											
											this.AppendEditViewFields(m_sMODULE + "." + LayoutEditView, tblMain, rdr);
											// 03/20/2008 Paul.  Dynamic buttons need to be recreated in order for events to fire. 
											ctlDynamicButtons.AppendButtons(m_sMODULE + "." + LayoutEditView, Sql.ToGuid(rdr["ASSIGNED_USER_ID"]), rdr);
											// 01/31/2006 Paul.  Save all data to be used later. 
											// 11/22/2010 Paul.  Convert data reader to data table for Rules Wizard. 
											// 05/25/2011 Paul.  Instead of using ViewState, load the previous record and let the DynamicControl use it if necessary. 
											/*
											for ( int i=0; i < dtCurrent.Columns.Count; i++ )
											{
												ViewState[dtCurrent.Columns[i].ColumnName] = rdr[dtCurrent.Columns[i].ColumnName];
											}
											*/
											// 05/25/2011 Paul.  Apply Business Rules. 
											this.ApplyEditViewPostLoadEventRules(m_sMODULE + "." + LayoutEditView, rdr);
										}
										else
										{
											// 11/25/2006 Paul.  If item is not visible, then don't allow save 
											// 03/20/2008 Paul.  Dynamic buttons need to be recreated in order for events to fire. 
											ctlDynamicButtons.AppendButtons(m_sMODULE + "." + LayoutEditView, Guid.Empty, null);
											ctlDynamicButtons.DisableAll();
											ctlDynamicButtons.ErrorText = L10n.Term("ACL.LBL_NO_ACCESS");
										}
									}
								}
							}
						}
					}
					else
					{
						this.AppendEditViewFields(m_sMODULE + "." + LayoutEditView, tblMain, null);
						// 03/20/2008 Paul.  Dynamic buttons need to be recreated in order for events to fire. 
						ctlDynamicButtons.AppendButtons(m_sMODULE + "." + LayoutEditView, Guid.Empty, null);
					}
				}
				else
				{
					// 12/02/2005 Paul.  When validation fails, the header title does not retain its value.  Update manually. 
					ctlModuleHeader.Title = L10n.Term("Leads.LBL_CONVERTLEAD");
					SetPageTitle(L10n.Term(".moduleList." + m_sMODULE) + " - " + ctlModuleHeader.Title);
				}
			}
			catch(Exception ex)
			{
				SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
				ctlDynamicButtons.ErrorText = ex.Message;
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			ctlDynamicButtons.Command += new CommandEventHandler(Page_Command);
			m_sMODULE = "Leads";
			LayoutEditView = "ConvertView";
			if ( IsPostBack )
			{
				// 12/02/2005 Paul.  Need to add the edit fields in order for events to fire. 
				this.AppendEditViewFields(m_sMODULE + "." + LayoutEditView, tblMain, null);
				// 03/20/2008 Paul.  Dynamic buttons need to be recreated in order for events to fire. 
				ctlDynamicButtons.AppendButtons(m_sMODULE + "." + LayoutEditView, Guid.Empty, null);
			}
		}
		#endregion
	}
}


